/**
 * 
 */
package net.iusr.jrules.eclipse.rules.quickfixes;

import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.tptp.platform.analysis.codereview.java.quickfix.JavaCodeReviewQuickFix;

/**
 * 
 * @author <a href="mailto:iusr.jar@gmail.com">IUSR</a>
 * @since 2006-11-13 下午09:38:20
 * @version $Revision$
 */
public class RedundantMethodsQuickFix extends JavaCodeReviewQuickFix {

	public TextEdit fixCodeReviewResult (ASTNode theNode, IDocument docToChange ) {
		MethodDeclaration md = getOwnedMethod(theNode);
		if(md == null) {
			return null;
		}
		ASTRewrite rewrite = ASTRewrite.create(md.getAST());
		rewrite.remove(md, null);
		return rewrite.rewriteAST(docToChange, null);
	}

    /**
     * Returns the ASTNode of type TYPE_DECLARATION or ANONYMOUS_CLASS_DECLARATION
     * that encloses the given node.
     * It returns null if there is not enclosing node of those types
     */
    ASTNode getEnclosingClass(ASTNode node) {
		ASTNode currentNode = node;
		while (currentNode != null &&
				currentNode.getNodeType() != ASTNode.TYPE_DECLARATION &&
				currentNode.getNodeType() != ASTNode.ANONYMOUS_CLASS_DECLARATION) {
			currentNode = currentNode.getParent();
		}
		return currentNode;
	}

    MethodDeclaration getOwnedMethod(ASTNode node) {
    	while(	node != null &&
    			node.getNodeType() != ASTNode.METHOD_DECLARATION &&
    			node.getNodeType() != ASTNode.METHOD_DECLARATION) {
    		node = node.getParent();
    	}
    	return (MethodDeclaration) node;
    }
}
